<template>
  <view class="page-container">
    <!-- 自定义可滑动标签页 -->
    <scroll-view 
      class="custom-tabs" 
      scroll-x="true" 
      scroll-with-animation="true"
      :scroll-left="scrollLeft"
      show-scrollbar="false"
      @scroll="onScroll"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
    >
      <view class="tab-container">
        <view 
          v-for="(tab, index) in tabs" 
          :key="tab.id"
          :id="'tab-'+index"
          :class="{ 'tab-active': tabIndex === index }"
          @click="switchTab(index)"
          class="tab-item">
          {{ tab.name }}
        </view>
      </view>
    </scroll-view>
    
    <!-- 内容区域 -->
    <view class="content-container">
      <view v-if="!isLoading && newsList.length === 0" class="empty-tip">
        <text>暂无内容</text>
      </view>
      
      <view v-else-if="newsList.length > 0" class="news-list">
        <view v-for="news in newsList" :key="news._id" class="news-item" @click="viewNewsDetail(news._id)">
          <image :src="news.cover" mode="aspectFill" class="news-cover"></image>
          <view class="news-info">
            <view class="news-title">{{ news.title }}</view>
            <view class="news-meta">
              <text class="news-category">{{ getCategoryName(news.category_id) }}</text>
              <text class="news-date">{{ formatDate(news.publish_date) }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <view v-if="isLoading" class="loading-state">
        <uni-load-more status="loading"></uni-load-more>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabIndex: 0,
      tabs: [],
      newsList: [],
      categoryMap: {},
      isLoading: true,
      scrollLeft: 0,
      tabWidths: [],
      tabPositions: [],
      windowWidth: 375, // 默认值，会在onLoad中更新
      touchStartX: 0,
      touchStartTime: 0,
      isScrolling: false,
      isClick: true
    }
  },
  onLoad() {
    this.windowWidth = uni.getSystemInfoSync().windowWidth;
    this.initData();
  },
  onReady() {
    this.initTabs();
  },
  methods: {
    async initData() {
      try {
        this.isLoading = true;
        
        // 获取分类数据
        const categoryRes = await uniCloud.callFunction({
          name: 'category',
          data: { type: 'get' }
        });
        
        if (categoryRes.result?.data?.length) {
          this.tabs = categoryRes.result.data.map(item => ({
            id: item._id,
            name: item.name
          }));
          
          // 创建分类映射
          this.categoryMap = this.tabs.reduce((map, tab) => {
            map[tab.id] = tab.name;
            return map;
          }, {});
          
          // 获取新闻数据
          await this.loadNews(this.tabs[0].id);
        } else {
          this.useFallbackData();
        }
      } catch (e) {
        console.error('初始化失败:', e);
        this.useFallbackData();
      } finally {
        this.isLoading = false;
      }
    },
    
    
    
    async loadNews(categoryId) {
      try {
        this.isLoading = true;
        const newsRes = await uniCloud.callFunction({
          name: 'news',
          data: { categoryId }
        });
        
        this.newsList = newsRes.result?.data || [];
      } catch (e) {
        console.error('加载新闻失败:', e);
        this.newsList = [];
      } finally {
        this.isLoading = false;
      }
    },
    
    initTabs() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.calculateTabPositions();
        }, 300);
      });
    },
    
    calculateTabPositions() {
      const query = uni.createSelectorQuery().in(this);
      
      query.select('.custom-tabs').boundingClientRect(containerRect => {
        if (!containerRect) return;
        
        query.selectAll('.tab-item').boundingClientRect(rects => {
          if (!rects?.length) return;
          
          this.tabWidths = rects.map(rect => rect.width);
          
          // 计算每个标签的累计位置
          let position = 0;
          this.tabPositions = rects.map(rect => {
            const pos = position;
            position += rect.width + 24; // 加上margin
            return pos;
          });
          
          // 初始滚动到选中标签
          if (this.tabs.length > 0) {
            this.scrollToTab(this.tabIndex);
          }
        }).exec();
      }).exec();
    },
    
    onTouchStart(e) {
      this.touchStartX = e.touches[0].clientX;
      this.touchStartTime = Date.now();
      this.isScrolling = false;
      this.isClick = true;
    },
    
    onTouchMove(e) {
      const touchX = e.touches[0].clientX;
      const diffX = Math.abs(touchX - this.touchStartX);
      
      // 如果水平移动距离超过10px，认为是滚动操作
      if (diffX > 10) {
        this.isScrolling = true;
        this.isClick = false;
      }
    },
    
    onTouchEnd(e) {
      const touchEndX = e.changedTouches[0].clientX;
      const diffX = touchEndX - this.touchStartX;
      const duration = Date.now() - this.touchStartTime;
      
      // 如果是快速滑动（时间短且距离大），添加额外滚动效果
      if (duration < 300 && Math.abs(diffX) > 50) {
        const scrollAmount = diffX > 0 ? -100 : 100;
        this.scrollLeft = Math.max(0, Math.min(
          this.scrollLeft + scrollAmount,
          this.getMaxScrollLeft()
        ));
      }
    },
    
    getMaxScrollLeft() {
      if (!this.tabPositions.length) return 0;
      return Math.max(0, this.tabPositions[this.tabPositions.length-1] + this.tabWidths[this.tabWidths.length-1] - this.windowWidth);
    },
    
    switchTab(index) {
      // 如果是滚动操作，不触发标签切换
      if (!this.isClick) return;
      
      if (index === this.tabIndex) return;
      
      this.tabIndex = index;
      this.loadNews(this.tabs[index].id);
      this.scrollToTab(index);
    },
    
    scrollToTab(index) {
      if (!this.tabPositions.length || index >= this.tabPositions.length) return;
      
      const tabWidth = this.tabWidths[index];
      const tabPosition = this.tabPositions[index];
      
      // 计算滚动位置（使标签居中）
      let targetScrollLeft = tabPosition + tabWidth/2 - this.windowWidth/2;
      targetScrollLeft = Math.max(0, Math.min(
        targetScrollLeft,
        this.getMaxScrollLeft()
      ));
      
      // 使用setTimeout确保DOM已更新
      setTimeout(() => {
        this.scrollLeft = targetScrollLeft;
      }, 50);
    },
    
    onScroll(e) {
      this.scrollLeft = e.detail.scrollLeft;
    },
    
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`;
    },
    
    getCategoryName(categoryId) {
      return this.categoryMap[categoryId] || '其他';
    },
    
    viewNewsDetail(id) {
      uni.navigateTo({
        url: `/pages/news/detail?id=${id}`
      });
    }
  }
}
</script>

<style>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

/* 标签页样式 */
.custom-tabs {
  width: 100%;
  height: 90rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  white-space: nowrap;
  box-sizing: border-box;
  touch-action: pan-x; /* 明确允许水平滚动 */
  -webkit-overflow-scrolling: touch; /* 优化iOS滚动体验 */
}

.tab-container {
  display: inline-block;
  height: 100%;
  padding: 0 30rpx;
}

.tab-item {
  display: inline-block;
  height: 100%;
  padding: 0 32rpx;
  margin-right: 24rpx;
  font-size: 30rpx;
  color: #666;
  line-height: 90rpx;
  position: relative;
  touch-action: manipulation; /* 优化触摸交互 */
}

.tab-item:last-child {
  margin-right: 0;
}

.tab-active {
  color: #007AFF;
  font-weight: bold;
}

.tab-active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 6rpx;
  background-color: #007AFF;
  border-radius: 3rpx;
}

/* 内容区域样式 */
.content-container {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
  box-sizing: border-box;
}

.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
  color: #999;
  font-size: 28rpx;
}

.loading-state {
  padding: 40rpx 0;
  display: flex;
  justify-content: center;
}

.news-list {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.news-item {
  display: flex;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
}

.news-cover {
  width: 220rpx;
  height: 160rpx;
  flex-shrink: 0;
}

.news-info {
  flex: 1;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.news-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
  font-size: 24rpx;
}

.news-category {
  color: #007AFF;
  background-color: #f0f9ff;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
}

.news-date {
  color: #999;
}
</style>